<?php

namespace app\service;

use plugin\admin\app\model\Lplog;
use plugin\admin\app\model\Lptime;
use support\Db;

class Fxlog
{
    public function fx()
    {
        Lplog::query()->where('is_run', 0)->chunk(100,function ($items)
        {
            foreach ($items as $item){
                $item->is_run = 1;

                $params = json_decode($item->params,true);
                $header = json_decode($item->header,true);

                if (isset($params['fbclid']) && trim($params['fbclid'])){
                    $item->fbclid = trim($params['fbclid']);
                }

                if (isset($params['campaign_id']) && trim($params['campaign_id'])){
                    $item->campaign_id = trim($params['campaign_id']);
                }

                if (isset($header['x-real-ip']) && trim($header['x-real-ip'])){
                    $item->ip = $header['x-real-ip'];
                }

                if (isset($header['host']) && trim($header['host'])){
                    $item->host = $header['host'];
                }

                $item->save();
            }

        });


        for ($i=0;$i >= -1;$i--)
        {
            $d = date('Ymd',strtotime($i.' day'));
            $this->_d($d);
        }

    }


    /**
     * 处理
     * @param $d
     * @return void
     */
    private function _d($d): void
    {
        $results = DB::select('select count(id)as num,d,fbclid,ip,`host`,campaign_id from wa_lplog where is_run=1 and d=:d GROUP BY ip,`host`,campaign_id', [
            'd' => $d,
        ]);
        if (!empty($results))
        {
            foreach ($results as $result){

                $inRow = [
                    'ip' => $result->ip,
                    'host' => $result->host,
                    'campaign_id' => $result->campaign_id,
                    'd' => date('Y-m-d',strtotime($result->d)),
                    'fbclid_md5' => $result->fbclid ? md5($result->fbclid) :'',
                    'spent_time' => ($result->num-1) * 2 + 1
                ];
                $this->_in($inRow);
            }
        }
    }


    /**
     * 入库
     * @param $row
     * @return void
     */
    private function _in($row): void
    {
        foreach ($row as $k => $v){
            if (!trim($v)){
                unset($row[$k]);
            }
        }

        $where = [];
        foreach (['ip','host','campaign_id'] as $f){
            if (isset($row[$f])){
                $where[] = [$f,'=',$row[$f]];
            }
        }

        $value = Lptime::query()->where($where)->value('id');
        if ($value){
            Lptime::query()->where('id',$value)->update($row);
        }else{
            Lptime::query()->create($row);
        }
    }
}